package com.cloudstudy.tool;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FileTool {
	public static String pathSeparator = initPathSeparator();

	private static String initPathSeparator() {
		Map os=System.getenv();
		String temp = "/";
		if (os.containsKey("OS")) {
			temp = "\\";
		}
		return temp;
	}

	public static String getExtention(String filePath) {
		int pos = filePath.lastIndexOf(".");
		String exname = filePath.substring(pos);
		return exname;
	}

	public static String getFileName(String filePath) {
		int pos = filePath.lastIndexOf(pathSeparator);
		return filePath.substring(pos);
	}

	public static List<File> getfilelist(String paths) {
		List flist = new ArrayList();
		File d = new File(paths);

		File[] lists = d.listFiles();

		for (int i = 0; i < lists.length; i++) {
			if (lists[i].isFile()) {
				flist.add(lists[i]);
			}

		}
		return flist;

	}

	public static List getDirlist(String paths) {
		List l1 = new ArrayList();
		File d = new File(paths);

		File lists[] = d.listFiles();

		for (int i = 0; i < lists.length; i++) {
			if (lists[i].isDirectory()) {
				l1.add(lists[i].getName().toString());
			}

		}
		return l1;

	}

	public static void deleteFile(String path) {
		File d = new File(path);
		File lists[] = d.listFiles();

		for (int i = 0; i < lists.length; i++) {
			if (lists[i].isFile()) {
				lists[i].delete();
			}

		}
	}

	public static void deleteFile(String dirPath, String filename) {
		File d = new File(dirPath);
		File lists[] = d.listFiles();

		for (int i = 0; i < lists.length; i++) {
			if (lists[i].getName().equals(filename))

				lists[i].delete();

		}
	}

	public static void deletedir(String dirPath) {
		File d = new File(dirPath);
		File lists[] = d.listFiles();
		for (int i = 0; i < lists.length; i++) {

			if (lists[i].isDirectory()) {
				String p = lists[i].getAbsolutePath();
				File f1 = new File(p);
				System.out.println(f1);
				f1.delete();
				try {
					Runtime.getRuntime().exec("rd " + p + "  /s /q");
				} catch (Exception e) {
					LogTool.error(FileTool.class, e);
				}
			}
		}

	}

	public static void saveObjectToFile(Object obj, String filepath) {
		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(new FileOutputStream(filepath));
			out.writeObject(obj);
			out.flush();
			out.close();
			System.out.println("save object success");
		} catch (Exception e) {
			LogTool.error(FileTool.class, e);
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					LogTool.error(FileTool.class, e);
				}
			}
		}

	}

	/**
	 * 插入行
	 * 
	 * @param filePath
	 * @throws IOException
	 */
	public static void addLine(String filePath, String line) throws IOException {
		BufferedWriter bw = null;
		bw = new BufferedWriter(new FileWriter(filePath, true));
		bw.write(line);
		bw.newLine();
		LogTool.debug(FileTool.class, "file add success");
		bw.flush();
		bw.close();

	}

	public static Object getObjectFromFile(String filepath) {
		Object obj = null;
		ObjectInputStream in = null;
		try {
			in = new ObjectInputStream(new FileInputStream(filepath));
			obj = in.readObject();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return obj;
	}

	public static void saveStringToFile(String s, String filePath) {
		DataOutputStream out = null;
		try {
			int index = filePath.lastIndexOf(pathSeparator);
			String folderPath = filePath.substring(0, index);
			// System.out.println("folderPath:"+folderPath);
			if (!isExist(folderPath)) {
				createFolder(folderPath);
			}
			out = new DataOutputStream(new FileOutputStream(filePath));
			byte[] bytes = s.getBytes("UTF-8");
			out.write(bytes);
			// out.writeUTF(obj);
			out.flush();
			out.close();
			System.out.println("save String success");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void saveStringToFile(String s, String filepath, String encode) {
		DataOutputStream out = null;
		try {
			out = new DataOutputStream(new FileOutputStream(filepath));
			byte[] bytes = s.getBytes(encode);
			out.write(bytes);
			out.flush();
			out.close();
			System.out.println("save String success");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void saveBytesToFile(byte[] bytes, String filepath) {
		DataOutputStream out = null;
		try {
			out = new DataOutputStream(new FileOutputStream(filepath));
			out.write(bytes);
			out.flush();
			out.close();
			System.out.println("save bytes success");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static String readFile(String filePath) {
		String encode = FileTool.getEncode(filePath);
		String str = "";
		try {
			FileInputStream in = new FileInputStream(filePath);
			InputStreamReader isr = new InputStreamReader(in, encode);
			BufferedReader reader = new BufferedReader(isr);
			String tempStr;
			while ((tempStr = reader.readLine()) != null) {
				str = str + tempStr;
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}

	public static String changeEncode(String string, String code) {
		byte[] bt = string.getBytes();
		try {
			string = new String(bt, code);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return string;
	}

	public static void createFolder(String folderPath) {
		String filePath = folderPath;
		File myFile = new File(filePath);
		try {
			if (myFile.isDirectory()) {
				LogTool.debug(FileTool.class, "the folder is exists:"
						+ folderPath);
			} else {
				myFile.mkdirs();
				LogTool.debug(FileTool.class, "create folder success:"
						+ folderPath);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 判断文件是否存在
	 *
	 * @param filePath
	 * @return
	 */
	public static boolean isExist(String filePath) {
		boolean result = false;
		File myFile = new File(filePath);
		try {
			if (myFile.isFile() || myFile.isDirectory() || myFile.isHidden()) {
				result = true;
				LogTool.debug(FileTool.class, "the file is exists!" + filePath);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static byte[] getBytes(File file) throws IOException {

		InputStream is = new FileInputStream(file);

		// 获取文件大小

		long length = file.length();

		if (length > Integer.MAX_VALUE) {

			// 文件太大，无法读取

			throw new IOException("File is to large " + file.getName());

		}

		// 创建一个数据来保存文件数据

		byte[] bytes = new byte[(int) length];

		// 读取数据到byte数组中

		int offset = 0;

		int numRead = 0;

		while (offset < bytes.length

		&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {

			offset += numRead;

		}
		// 确保所有数据均被读取

		if (offset < bytes.length) {

			throw new IOException("Could not completely read file "
					+ file.getName());

		}

		is.close();

		return bytes;
	}

	/**
	 * 改过
	 * @param filePath
	 * @return
	 */
	public static String getEncode(String filePath) {
		String encode = "";
		int encoding = new BytesEncodingDetectTool().detectEncoding(new File(filePath));
		if (encoding == 0 || encoding == 1) {
			encode = "gbk";
		}else if(encoding == 6 || encoding == 7 || encoding == 8) {
			encode = "utf-8";
		}else {
			encode = "UNICODE";
		}
		return encode;
	}

	public static void main(String args[]) throws Exception {
		// FileTool.createFolder("F://mactest");
		// FileTool.createFolder("F://mactest//test//test2");
		// String f="F://mactest//demo-request.xml";
		// String encode=FileTool.getEncode(f);
		// System.out.println(encode);
		//String filePath = "d:\\test\\test.txt";

		//FileTool.saveStringToFile("test create file", System.getenv().get("OS").toLowerCase());
		 System.out.println("==========="+System.getenv().get("OSTYPE"));
	}

}
